package com.hry.fileupload;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author: HRYing
 * @Date: 2022/2/17 22:30
 * @Description: TODO
 */
@RestController
public class FileuploadController {

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    @PostMapping("/upload")
    public Map<String, Object> fileupload(MultipartFile file, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String format = sdf.format(new Date());
        // String realPath = request.getServletContext().getRealPath("/") + format;
        String realPath = "Y:\\node\\file" + format;
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        try {
            System.out.println(realPath);
            file.transferTo(new File(folder, newName));
//            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + format + newName;
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/file" + format + newName;
            System.out.println(url);
            result.put("status", "OK");
            result.put("name", oldName);
            result.put("url", url);
        } catch (IOException e) {
            result.put("status", "ERROR");
            result.put("msg", e.getMessage());
        }
        return result;
    }

}
